/**
 * 图片管理器 - 内存优化版本
 */

import { memoryManager } from './performance.js';

export class ImageManager {
  constructor(options = {}) {
    this.options = {
      maxCacheSize: 50,           // 最大缓存图片数量
      maxImageSize: 5 * 1024 * 1024, // 最大图片大小（5MB）
      enableCompression: true,     // 启用压缩
      compressionQuality: 0.8,     // 压缩质量
      enableLazyLoad: true,        // 启用懒加载
      enableWebP: true,           // 启用WebP格式
      ...options
    };
    
    this.imageCache = new Map();
    this.loadingImages = new Set();
    this.failedImages = new Set();
    this.observer = null;
    
    this.initLazyLoad();
  }
  
  // 初始化懒加载
  initLazyLoad() {
    if (!this.options.enableLazyLoad) return;
    
    if ('IntersectionObserver' in window) {
      this.observer = new IntersectionObserver(
        this.handleIntersection.bind(this),
        {
          root: null,
          rootMargin: '50px',
          threshold: 0.1
        }
      );
    }
  }
  
  // 处理图片进入视口
  handleIntersection(entries) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        this.loadImage(img);
        this.observer.unobserve(img);
      }
    });
  }
  
  // 加载图片
  async loadImage(img) {
    const src = img.dataset.src || img.src;
    if (!src) return;
    
    // 检查缓存
    const cachedImage = this.getCachedImage(src);
    if (cachedImage) {
      this.setImageSrc(img, cachedImage);
      return;
    }
    
    // 检查是否正在加载
    if (this.loadingImages.has(src)) {
      return;
    }
    
    // 检查是否加载失败
    if (this.failedImages.has(src)) {
      this.setErrorImage(img);
      return;
    }
    
    try {
      this.loadingImages.add(src);
      
      // 加载图片
      const imageData = await this.fetchImage(src);
      
      // 压缩图片
      const compressedData = await this.compressImage(imageData);
      
      // 缓存图片
      this.cacheImage(src, compressedData);
      
      // 设置图片
      this.setImageSrc(img, compressedData);
      
    } catch (error) {
      console.error('Image load error:', error);
      this.failedImages.add(src);
      this.setErrorImage(img);
    } finally {
      this.loadingImages.delete(src);
    }
  }
  
  // 获取缓存的图片
  getCachedImage(src) {
    const cached = this.imageCache.get(src);
    if (cached) {
      cached.lastAccess = Date.now();
      return cached.data;
    }
    return null;
  }
  
  // 缓存图片
  cacheImage(src, data) {
    // 检查缓存大小
    if (this.imageCache.size >= this.options.maxCacheSize) {
      this.evictOldestImage();
    }
    
    this.imageCache.set(src, {
      data,
      timestamp: Date.now(),
      lastAccess: Date.now(),
      size: this.estimateImageSize(data)
    });
  }
  
  // 获取图片
  async fetchImage(src) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      
      img.onload = () => {
        // 检查图片大小
        if (this.estimateImageSize(img) > this.options.maxImageSize) {
          reject(new Error('Image too large'));
          return;
        }
        
        // 转换为canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.width = img.width;
        canvas.height = img.height;
        
        ctx.drawImage(img, 0, 0);
        
        resolve(canvas);
      };
      
      img.onerror = () => {
        reject(new Error('Image load failed'));
      };
      
      img.src = src;
    });
  }
  
  // 压缩图片
  async compressImage(canvas) {
    if (!this.options.enableCompression) {
      return canvas.toDataURL('image/jpeg', 1.0);
    }
    
    // 检查是否支持WebP
    const format = this.options.enableWebP && this.supportsWebP() ? 'image/webp' : 'image/jpeg';
    const quality = this.options.compressionQuality;
    
    return canvas.toDataURL(format, quality);
  }
  
  // 检查WebP支持
  supportsWebP() {
    const canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
  }
  
  // 设置图片源
  setImageSrc(img, data) {
    img.src = data;
    img.classList.add('loaded');
    img.classList.remove('loading', 'error');
  }
  
  // 设置错误图片
  setErrorImage(img) {
    img.src = this.getErrorImageSrc();
    img.classList.add('error');
    img.classList.remove('loading', 'loaded');
  }
  
  // 获取错误图片源
  getErrorImageSrc() {
    // 返回默认错误图片
    return '';
  }
  
  // 估算图片大小
  estimateImageSize(img) {
    if (img.width && img.height) {
      return img.width * img.height * 4; // RGBA
    }
    return 0;
  }
  
  // 驱逐最旧的图片
  evictOldestImage() {
    let oldestKey = null;
    let oldestTime = Date.now();
    
    for (const [key, item] of this.imageCache.entries()) {
      if (item.lastAccess < oldestTime) {
        oldestTime = item.lastAccess;
        oldestKey = key;
      }
    }
    
    if (oldestKey) {
      this.imageCache.delete(oldestKey);
    }
  }
  
  // 观察图片元素
  observe(img) {
    if (this.observer && this.options.enableLazyLoad) {
      this.observer.observe(img);
    } else {
      // 直接加载
      this.loadImage(img);
    }
  }
  
  // 停止观察图片元素
  unobserve(img) {
    if (this.observer) {
      this.observer.unobserve(img);
    }
  }
  
  // 预加载图片
  async preloadImages(urls) {
    const promises = urls.map(url => this.preloadImage(url));
    return Promise.allSettled(promises);
  }
  
  // 预加载单个图片
  async preloadImage(url) {
    try {
      const imageData = await this.fetchImage(url);
      const compressedData = await this.compressImage(imageData);
      this.cacheImage(url, compressedData);
      return compressedData;
    } catch (error) {
      console.error('Preload error:', error);
      throw error;
    }
  }
  
  // 清理缓存
  clearCache() {
    this.imageCache.clear();
    this.loadingImages.clear();
    this.failedImages.clear();
  }
  
  // 获取缓存统计
  getCacheStats() {
    let totalSize = 0;
    for (const item of this.imageCache.values()) {
      totalSize += item.size;
    }
    
    return {
      cacheSize: this.imageCache.size,
      totalSize: Math.round(totalSize / 1024), // KB
      loadingCount: this.loadingImages.size,
      failedCount: this.failedImages.size
    };
  }
  
  // 销毁管理器
  destroy() {
    if (this.observer) {
      this.observer.disconnect();
    }
    this.clearCache();
  }
}

// 图片懒加载指令
export const lazyLoadDirective = {
  bind(el, binding) {
    const imageManager = binding.value || window.imageManager;
    if (imageManager) {
      imageManager.observe(el);
    }
  },
  
  unbind(el, binding) {
    const imageManager = binding.value || window.imageManager;
    if (imageManager) {
      imageManager.unobserve(el);
    }
  }
};

// 导出单例实例
export const imageManager = new ImageManager();

// 全局注册
if (typeof window !== 'undefined') {
  window.imageManager = imageManager;
}
